package com.study.mongodbdynamicdatasource.anno;

import com.study.mongodbdynamicdatasource.config.MongoDbContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.MessageFormat;

/**
 * @Name: MongoDS
 * @Description: java类作用描述
 * @Author: yn
 * @CreateDate: 2023/6/9 15:34
 * @Remark: 特殊说明
 * @Version: 1.0
 */
@Component
@Aspect
@Order(value = -99)
@Slf4j
public class MongoDbSwitch {
	@Pointcut("@annotation(MongoDS)")
	private void mongoDS(){}

	@Before("mongoDS()")
	public void before(JoinPoint point) {
		try {
			MethodSignature methodSignature = (MethodSignature) point.getSignature();
			Method method =
					point
							.getTarget()
							.getClass()
							.getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
			MongoDS mongoDS = method.getAnnotation(MongoDS.class);
			log.info(MessageFormat.format("切换 {0}数据源", mongoDS.value()));
			MongoDbContext.pushMongoDatabaseFactory(mongoDS.value());
			MongoDbContext.setNotSwitchDynamicallyIdentities();
		} catch (Exception e) {
			log.error("==========>前置mongo数据源切换异常", e);
		}
	}

	@After("mongoDS()")
	public void after(JoinPoint point) {
		try {
			log.info("移除mongo数据源上下文");
			MongoDbContext.setSwitchDynamicallyIdentities();
			MongoDbContext.removeMongoDbFactory();
		} catch (Exception e) {
			log.error("==========>后置mongo数据源切换异常", e);
		}
	}
}
